import { emitter } from "@/libs";
import BattleService from "@/services/BattleService";
import { useStore } from "@/store";
import { ElMessageBox } from "element-plus";

const joinRoom = (id: number, seatNumber: number, isRobot: boolean,password:string) => {
  return BattleService.joinRoom({
    seat_no: seatNumber,
    room_id: id,
    is_robot: isRobot,
    password:password
  });
};

export const useJoinRoom = () => {
  const store = useStore();

  return async (id: number, seatNumber: number, price: number, isRobot = false,password) => {
    return new Promise((resolve, reject) => {
      const userInfo = store.getters.userInfo;

      if (!userInfo) {
        emitter.emit("login");
        return reject();
      }

      const join = () => {
        return joinRoom(id, seatNumber, isRobot,password).then(resolve).catch(reject);
      }

      ElMessageBox.confirm(isRobot ? '确定添加机器人加入对战吗？' : `是否确认消耗${price.toFixed(2)}硬币加入该房间？`, '提示', {
        customClass: "custom-message-box",
        lockScroll: false,
      }).then(() => {
        return join();
      }).catch(reject);
    })
  }
}
